package com.xd.pre.modules.security.ldap.userdetails;

import com.xd.pre.security.LoginType;
import com.xd.pre.security.PreSecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;

import java.util.Collection;

@Slf4j
public class PreLdapUserDetailsMapper extends LdapUserDetailsMapper {
    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
                                          Collection<? extends GrantedAuthority> authorities) {
        UserDetails userDetails = super.mapUserFromContext(ctx, username, authorities);
        log.info("{}", userDetails);

        //TODO 这里要将新用户入库！以便统一管理的授权，如果不入库的话可以通过查询ldap库对用户授权，但可能不方便管理
        return new PreSecurityUser(0, userDetails.getUsername(), userDetails.getPassword(),
                userDetails.getAuthorities(), LoginType.normal);
    }
}
